package com.puccampinas.finalproject.core.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.lang3.StringUtils;

import com.google.gson.Gson;
import com.puccampinas.finalproject.core.logs.LogUtils;
import com.puccampinas.finalproject.core.logs.LoggerType;


public class HttpUtil {
    
	public static String getResponse(String address) throws Exception {
        LogUtils.info(LoggerType.REQUESTS_PERFORMED, "Requesting: " + address);

        URL url;
        HttpURLConnection conn = null;
        String result = "";
		try {
		    BufferedReader rd;
		    String line;
		    url = new URL(address);
		    
		    conn = (HttpURLConnection) url.openConnection();
		    conn.setRequestMethod("GET");
	        rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	        
	        
	        while ((line = rd.readLine()) != null) {
	            result += line;
	        }
	        rd.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
        return result;
    }
    
    
    public static String[] parseJsonToArray(String json) {
    	String[] target = null;
    	if (StringUtils.isNotEmpty(json)) {
	    	Gson gson = new Gson();
			target = gson.fromJson(json,String[].class);
		}	
		return target;
    }
}